// src/pages/EmployeePrinter.jsx
import React, { useRef, useState } from 'react';
import { Card, Button, Modal, Checkbox, Row, Col, InputNumber, Space, Tooltip } from 'antd';
import { PrinterOutlined, SettingOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import PrinterLayout from '../layouts/PrinterLayout.jsx';
import printJS from 'print-js';

const EmployeePrinter = () => {
    const [data] = useState([
        {
            key: '1',
            name: '张三',
            age: 32,
            address: '北京市朝阳区建国门外大街1号国贸大厦A座',
            department: '技术部',
            position: '高级前端工程师',
            salary: 25000,
            joinDate: '2020-03-15',
        },
        {
            key: '2',
            name: '李四',
            age: 28,
            address: '上海市浦东新区陆家嘴环路100号环球金融中心',
            department: '产品部',
            position: '产品经理',
            salary: 22000,
            joinDate: '2019-07-22',
        },
        {
            key: '3',
            name: '王五',
            age: 35,
            address: '广州市天河区珠江新城华夏路10号富力中心',
            department: '市场部',
            position: '市场总监',
            salary: 35000,
            joinDate: '2018-11-05',
        },
        {
            key: '4',
            name: '赵六',
            age: 26,
            address: '深圳市南山区科技园南区高新南一道9号',
            department: '设计部',
            position: 'UI设计师',
            salary: 18000,
            joinDate: '2021-01-30',
        },
        {
            key: '5',
            name: '钱七',
            age: 30,
            address: '杭州市西湖区文一西路969号阿里巴巴西溪园区',
            department: '研发部',
            position: '后端工程师',
            salary: 28000,
            joinDate: '2019-09-12',
        },
    ]);

    const allColumns = [
        { title: '姓名', dataIndex: 'name', key: 'name', width: 100, defaultVisible: true },
        { title: '年龄', dataIndex: 'age', key: 'age', width: 80, defaultVisible: true },
        { title: '地址', dataIndex: 'address', key: 'address', width: 200, defaultVisible: true },
        { title: '部门', dataIndex: 'department', key: 'department', width: 120, defaultVisible: true },
        { title: '职位', dataIndex: 'position', key: 'position', width: 150, defaultVisible: true },
        { title: '薪资', dataIndex: 'salary', key: 'salary', width: 120, defaultVisible: false },
        { title: '入职日期', dataIndex: 'joinDate', key: 'joinDate', width: 120, defaultVisible: false },
    ];

    const [visibleCols, setVisibleCols] = useState(allColumns.filter(c => c.defaultVisible).map(c => c.key));
    const [colWidths, setColWidths] = useState(Object.fromEntries(allColumns.map(c => [c.key, c.width])));
    const [showSettings, setShowSettings] = useState(false);
    const [showHelp, setShowHelp] = useState(false);

    const printRef = useRef();

    const getColumns = () =>
        allColumns
            .filter(col => visibleCols.includes(col.key))
            .map(col => ({
                ...col,
                width: colWidths[col.key],
                render: text => (
                    <div style={{ wordWrap: 'break-word', whiteSpace: 'pre-wrap', padding: '8px 0' }}>
                        {text}
                    </div>
                ),
            }));

    const handlePrint = () => {
        const printNode = printRef.current.cloneNode(true);
        // 移除滚动样式（关键步骤）
        const tableBody = printNode.querySelector('.ant-table-body');
        if (tableBody) {
            tableBody.style.maxHeight = 'unset';
            tableBody.style.overflowY = 'visible';
            tableBody.style.overflowX = 'visible';
        }
        printJS({
            printable: printNode.innerHTML,
            type: 'raw-html',
            documentTitle: '企业员工信息表',
            css: '.print-container { background-color: white; padding: 30px; }',
            onError: err => {
                console.error(err);
                Modal.error({ title: '打印错误', content: '打印失败，请重试。' });
            }
        });
    };

    return (
        <div >
            <Card
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <span>表格打印系统</span>
                        <Tooltip title="使用帮助">
                            <Button type="text" icon={<QuestionCircleOutlined />} onClick={() => setShowHelp(true)} />
                        </Tooltip>
                    </div>
                }
                extra={
                    <Space>
                        <Button type="primary" icon={<PrinterOutlined />} onClick={handlePrint}>打印</Button>
                        <Button icon={<SettingOutlined />} onClick={() => setShowSettings(!showSettings)}>
                            {showSettings ? '隐藏设置' : '显示设置'}
                        </Button>
                    </Space>
                }
            >
                {showSettings && (
                    <Card title="打印设置" style={{ marginBottom: 24 }}>
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <h3>选择打印列：</h3>
                                <Checkbox.Group value={visibleCols} onChange={setVisibleCols}>
                                    <Row>
                                        {allColumns.map(col => (
                                            <Col span={8} key={col.key}>
                                                <Checkbox value={col.key}>{col.title}</Checkbox>
                                            </Col>
                                        ))}
                                    </Row>
                                </Checkbox.Group>
                            </Col>
                            <Col span={24}>
                                <h3>设置列宽：</h3>
                                <Row gutter={[16, 16]}>
                                    {allColumns.map(col => (
                                        <Col span={6} key={col.key}>
                                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                                <span style={{ width: 70 }}>{col.title}:</span>
                                                <InputNumber
                                                    min={50}
                                                    max={500}
                                                    value={colWidths[col.key]}
                                                    onChange={val => setColWidths({ ...colWidths, [col.key]: val })}
                                                    disabled={!visibleCols.includes(col.key)}
                                                />
                                            </div>
                                        </Col>
                                    ))}
                                </Row>
                            </Col>
                        </Row>
                    </Card>
                )}

                <div ref={printRef}>
                    <PrinterLayout
                        title="企业员工信息表"
                        department="人力资源部"
                        columns={getColumns()}
                        data={data}
                    />
                </div>
            </Card>

            <Modal
                title="使用说明"
                open={showHelp}
                onCancel={() => setShowHelp(false)}
                footer={[<Button key="close" type="primary" onClick={() => setShowHelp(false)}>关闭</Button>]}
            >
                <p>1. 通过设置按钮配置需要打印的列与列宽。</p>
                <p>2. 点击“打印”按钮预览并打印当前表格。</p>
                <p>3. 打印前建议选择 A4 横向页面格式。</p>
            </Modal>
        </div>
    );
};

export default EmployeePrinter;
